<?php



/**

 * @author ducnhat

 * @email ddnhat@gmail.com

 * @copyright 2014

 */


class Admin_Model_Banner extends Zend_Db_Table
{


    protected $_name = "banners";

    protected $_primary = "id";


    public function saveData($data = array())
    {

        $db = Zend_Registry::get('db');


        $db->beginTransaction();


        try {

            if (isset($data['id']) && $this->checkExists($data['id'])) {

                $id = $data['id'];

                $db->update("banners", $data, "id = $id");

            } else {

                $db->insert('banners', $data);

            }


            $cache = new Zenddn_System_Cache();

            $cache->clean(array('banner'));


            $db->commit();


            return true;

        }
        catch (exception $e) {

            $db->rollBack();


            return false;

        }

    }


    public function getData($id = null)
    {

        $db = Zend_Registry::get('db');

        $db->setFetchMode(Zend_Db::FETCH_OBJ);


        $cols = array(
            'id',
            'name',
            'link',
            'image',
            'publish_date',
            'status');


        if ($id != null) {

            $cols = array(
                'id',
                'name',
                'link',
                'position',
                'image',
                'publish_date',
                'status');

        }


        $select = $db->select()->from(array('b' => 'banners'), $cols);


        if ($id != null) {

            $select->where("b.id = ?", $id, 'INTEGER');


            $db->setFetchMode(Zend_Db::FETCH_ASSOC);

            $result = $db->fetchRow($select);

        } else {

            $select->join(array('t' => 'taxonomy'), 't.id = b.position', 'name AS position')->
                order('b.id DESC');


            $result = $db->fetchAll($select);

        }


        return $result;

    }


    public function getAllData()
    {

        return $this->getData();

    }


    public function deleteData($id)
    {

        $db = Zend_Registry::get('db');


        $db->beginTransaction();


        try {

            $db->delete('banners', "id = $id");


            $cache = new Zenddn_System_Cache();

            $cache->clean(array('banner'));


            $db->commit();


            return true;

        }
        catch (exception $e) {

            $db->rollBack();


            return false;

        }

    }


    public function checkExists($id)
    {

        $option = array('table' => 'banners', 'field' => 'id');

        $validator = new Zend_Validate_Db_RecordExists($option);


        if ($validator->isValid($id)) {

            return true;

        }


        return false;

    }

}
